package pl.edu.uj.tcs.blef.protocol;

public class MsgRequestFactory implements RequestFactory {

	@Override
	public Request build(Object[] parameters, RequestHandler handler) throws BuildFailedException {
		if(parameters.length != 1) throw new BuildFailedException("One argument expected.");
		try{
			String msg = (String)parameters[0];
			return new MsgRequest("/msg "+msg, handler);
		} catch(ClassCastException e) { throw new BuildFailedException(e.getMessage()); }
	}

	@Override
	public Request parse(String message, RequestHandler handler) throws ParseFailedException, BuildFailedException {
		if("/msg".equals(message.split(" ")[0])){
			String[] tab = new String[1];
			StringBuilder sb = new StringBuilder();
			for(int i=1; i<message.split(" ").length; ++i){
				sb.append(message.split(" ")[i]);
				sb.append(" ");
			}
			
			tab[0] = sb.toString();
			return build(tab, handler);
		}
		else throw new ParseFailedException("Unknown request.");
	}
}
